package com.fulihui.information.core.repository.impl;

import com.fulihui.information.biz.conv.SourceConv;
import com.fulihui.information.common.ESortType;
import com.fulihui.information.core.repository.SourceRepository;
import com.fulihui.information.dal.dataobj.InfoSource;
import com.fulihui.information.dal.dataobj.InfoSourceExample;
import com.fulihui.information.dal.mapper.ExtInfoSourceMapper;
import com.fulihui.information.dal.mapper.InfoSourceMapper;
import com.fulihui.information.dto.SourceDTO;
import com.fulihui.information.request.SourceQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

import static org.near.toolkit.common.StringUtil.isNotBlank;

/**
 * 
 * Created by LeeSon on 2017/1/16 0016.
 */
@Repository
public class SourceRepositoryImpl implements SourceRepository {
    @Autowired
    private InfoSourceMapper    infoSourceMapper;
    @Autowired
    private ExtInfoSourceMapper extInfoSourceMapper;

    @Override
    public boolean modifyStatus(String code, String status) {
        InfoSource record = new InfoSource();
        record.setCode(code);
        record.setCheck(status);
        return infoSourceMapper.updateByPrimaryKeySelective(record) > 0;
    }

    @Override
    public List<SourceDTO> queryPage(SourceQueryRequest request) {
        return SourceConv.toList(extInfoSourceMapper.selectByExamplePage(
            buildInfoSourceExample(request), request.start4Mysql(), request.getRows()));
    }

    @Override
    public int queryPageCount(SourceQueryRequest request) {
        return extInfoSourceMapper.selectByExamplePageCount(buildInfoSourceExample(request));
    }

    private InfoSourceExample buildInfoSourceExample(SourceQueryRequest request) {
        InfoSourceExample example = new InfoSourceExample();
        InfoSourceExample.Criteria criteria = example.createCriteria();

        if (isNotBlank(request.getName())) {
            criteria.andNameLike("%" + request.getName() + "%");
        }

        if (isNotBlank(request.getCode())) {
            criteria.andCodeLike("%" + request.getCode() + "%");
        }

        if (isNotBlank(request.getStatus())) {
            criteria.andCheckEqualTo(request.getStatus());
        }

        example.setOrderByClause("gmt_create " + ESortType.DESC.getCode());

        return example;
    }
}